package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.MessageSenderContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.properties.MessageSenderProperties;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 推送到消息中心
 *
 * @author lilh
 * @date 2021/4/29 10:14
 */
@Slf4j
@Component
@EnableConfigurationProperties(MessageSenderProperties.class)
public class NotificationCenterMessageSender implements MessageSender, InitializingBean {

    private final BlockingQueue<MessageSenderContext> blockingQueue = new LinkedBlockingQueue<>();

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private MessageSenderProperties properties;

    private volatile boolean stop = false;


    @Override
    public boolean isEnable() {
        return properties.getNotificationCenter().isEnable();
    }

    @Override
    public boolean sendMessage(MessageSenderContext context) {
        log.info("往队列中加入一条消息：{}", JSONObject.toJSONString(context));
        return blockingQueue.add(context);
    }

    @Override
    public String getDescription() {
        return "推送消息到通知中心";
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        /**
        taskExecutor.execute(() -> {
            while (!stop) {
                try {
                    MessageSenderContext context = blockingQueue.take();
                    //推送消息
                    log.info("线程从队列中取出一条消息：{}", JSONObject.toJSONString(context));
                } catch (Exception e) {
                    log.warn("消息推送异常：{}", e);
                }
            }
        });
         */
    }

    public void setStop(boolean stop) {
        this.stop = stop;
    }
}
